﻿using Godot;
using System;

public class CanvasMover
{
    private bool _moveing;
    private Vector2 _offset;
    private Control _root;
    private Control _panent;
    private Action _refresh;
    private int _zoomIndex = 4;

    private static float[] _zooms = new float[] { 0.1f, 0.2f, 0.5f, 0.7f, 1f, 1.5f, 2f, 4f, 8f, 10f };
    public CanvasMover(Action refresh, Control root)
    {
        _refresh = refresh;
        _root = root;
        _panent = root.GetParentOrNull<Control>();
        _offset = Vector2.Zero;
        _moveing = false;
    }
    public bool Moveing => _moveing;
    public float Scale
    {
        get => _root.RectScale.x;
        set => _root.RectScale = new Vector2(value, value);
    }
    public Vector2 Offset
    {
        get => _root.RectPosition;
        set => _root.RectPosition = value;
    }
    public void ZoomIn()
    {
        var scale = Scale;
        scale *= 1.2f;
        if (scale > 12f)
            return;

        /*_zoomIndex++;
        if (_zoomIndex >= _zooms.Length)
            _zoomIndex = _zooms.Length - 1;*/
        Scale = scale;
        _refresh();
    }

    public void ZoomOut()
    {
        var scale = Scale;
        scale /= 1.2f;
        if (scale < 0.1f)
            return;
        Scale = scale;
        _refresh();

        /*_zoomIndex--;
        if (_zoomIndex < 0)
            _zoomIndex = 0;
        Scale = _zooms[_zoomIndex];
        _refresh();*/
    }
    public void Begin(Vector2 position)
    {
        _moveing = true;
        _offset = position - Offset;
        _refresh();
    }
    public void MoveTo(Vector2 position)
    {
        if (!_moveing) return;
        var size = _root.RectSize * Scale;
        var offset = position - _offset;
        var x = offset.x;
        var minX = -(size.x - 50);
        var maxX = (_panent.RectSize.x - 50);
        if (x < minX)
            offset.x = minX;
        if (x > maxX)
            offset.x = maxX;
        GD.Print(offset, "  ", minX, maxX);
        Offset = offset;

        _refresh();
    }
    public void End()
    {
        _offset = Vector2.Zero;
        _moveing = false;
        _refresh();
    }
}
